package com.lizba.redis.tx;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *      Redis事务demo
 * </p>
 *
 * @Author: Liziba
 * @Date: 2021/9/9 23:53
 */
public class TransactionDemo {

    private Jedis client;

    public TransactionDemo(Jedis client) {
        this.client = client;
    }

    /**
     * 添加余额
     *
     * @param userId    用户id
     * @param amt       添加余额
     * @return
     */
    public BigDecimal addBalance(String userId, BigDecimal amt) {
        String key = this.keyFormat(userId);
        // 初始用户余额为0
        client.setnx(key, "0");
        while (true) {
            client.watch(key);
            BigDecimal balance = new BigDecimal(client.get(key)).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal amount = balance.add(amt);
            Transaction tx = client.multi();
            tx.set(key, amount.toPlainString());
            List<Object> exec = tx.exec();
            // 返回值不为空则证明Redis事务成功
            if (exec != null) {
                break;
            }
        }
        return new BigDecimal(client.get(key)).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 获取总金额
     *
     * @param userId 用户id
     * @return
     */
    public BigDecimal getAmount(String userId) {
        String amt = client.get(keyFormat(userId));
        return new BigDecimal(amt);
    }

    /**
     * Redis key
     * @param userId 用户id
     * @return
     */
    private String keyFormat(String userId) {
        return String.format("balance:%s",userId);
    }

}
